# koroFileHeader at Yungoal acer
# Create: 2021-07-21 10:30:37
# LastEdit: 2021-07-23 13:50:47
"""说明暂无"""
__author__ = '749B'


import unittest
from unittest.mock import patch

if __name__ == '__main__':
    import os
    import sys
    sys.path.append(os.getcwd())

from msrestazure.azure_cloud import AZURE_CHINA_CLOUD
# pylint: disable = import-error
from azure_client.client import Azure_Client, Azure_Subscription_Client
from tests.azure_temp_resource import resource_guid


class SubscriptionsClientTestCase(unittest.TestCase):

    def setUp(self):
        # Azure_Client 没有 get_subscriptions 方法，会报 AttributeError。添加 create=True 可解决
        #patcher = patch('azure_client.client.Azure_Client.get_subscriptions', create=True)
        # 虽然调用时是调用父类的方法，但是最终执行的还是子类的方法。替换子类里实际调用的方法即可。
        patcher = patch('azure_client.client.Azure_Subscription_Client.get_subscriptions')
        self.addCleanup(patcher.stop)
        self.mock_method = patcher.start()
        self.mock_method.return_value = [
            {
                'id': '/subscriptions/%s' % resource_guid[1],
                'subscription_id': resource_guid[1],
                'display_name': 'Steed Xu',
                'tenant_id': resource_guid[0],
                'state': 'Enabled',
                'subscription_policies': {
                    'location_placement_id': 'China_2014-09-01', 
                    'quota_id': 'EnterpriseAgreement_2014-09-01',
                    'spending_limit': 'Off'},
                'authorization_source': 'RoleBased',
                'managed_by_tenants': []},
            {
                'id': '/subscriptions/%s' % resource_guid[2],
                'subscription_id': resource_guid[2],
                'display_name': 'Jeff Hee',
                'tenant_id': resource_guid[0],
                'state': 'Enabled',
                'subscription_policies': {
                    'location_placement_id': 'China_2014-09-01',
                    'quota_id': 'EnterpriseAgreement_2014-09-01',
                    'spending_limit': 'Off'},
                'authorization_source': 'RoleBased',
                'managed_by_tenants': []},
            {
                'id': '/subscriptions/%s' % resource_guid[3],
                'subscription_id': resource_guid[3],
                'display_name': 'MAJAC',
                'tenant_id': resource_guid[0],
                'state': 'Enabled',
                'subscription_policies': {
                    'location_placement_id': 'China_2014-09-01',
                    'quota_id': 'EnterpriseAgreement_2014-09-01',
                    'spending_limit': 'Off'},
                'authorization_source': 'RoleBased',
                'managed_by_tenants': []},
            {
                'id': '/subscriptions/%s' % resource_guid[4],
                'subscription_id': resource_guid[4],
                'display_name': 'steeed.gitee.io',
                'tenant_id': resource_guid[0],
                'state': 'Enabled',
                'subscription_policies': {
                    'location_placement_id': 'China_2014-09-01',
                    'quota_id': 'EnterpriseAgreement_2014-09-01',
                    'spending_limit': 'Off'},
                'authorization_source': 'RoleBased',
                'managed_by_tenants': []},
            {
                'id': '/subscriptions/%s' % resource_guid[5],
                'subscription_id': resource_guid[5],
                'display_name': 'APP PORTAL',
                'tenant_id': resource_guid[0],
                'state': 'Enabled',
                'subscription_policies': {
                    'location_placement_id': 'China_2014-09-01',
                    'quota_id': 'EnterpriseAgreement_2014-09-01',
                    'spending_limit': 'Off'},
                'authorization_source': 'RoleBased',
                'managed_by_tenants': [{'tenant_id': resource_guid[6]}]}
        ]

        if Azure_Client._instance is None:
            # 类是单例模式，第一次正常实例化
            self.client = Azure_Client(AZURE_CHINA_CLOUD)
        else:
            self.client = Azure_Client(AZURE_CHINA_CLOUD)
            # 单例模式由于不会再次执行构造方法，会有问题。self.client.get_subscriptions方法是在构造函数中生成的
            # 之前的实例中的self.client.get_subscriptions方法已经存在，已经指向了替换前的方法
            # 这里期望是通过Azure_Subscription_Client间接指向到替换的方法
            self.client.get_subscriptions = Azure_Subscription_Client.get_subscriptions

    def test_get_subscriptions(self):
        """确认get_subscriptions方法已经被替换了，无论是从父类调用还是从子类调用"""
        self.assertIs(self.client.subscription_client.get_subscriptions, self.mock_method)
        # 父类方法的id可能会不同，去掉单例模式后就一致了
        self.assertIs(self.client.get_subscriptions, self.mock_method)
        # 可以比较父类方法和子类方法返回的结果是否一致，上面ID都一致了，这个比较返回结果就多余了
        self.assertEqual(self.client.get_subscriptions(), self.client.subscription_client.get_subscriptions())

    def test_get_subscriptionid_by_name(self):
        """测试方法：get_subscriptionid_by_name"""
        table = [
            ('NotExistName', None),
            ('Steed Xu', resource_guid[1]),
            ('Jeff Hee', resource_guid[2]),
            ('MAJAC', resource_guid[3]),
            ('steeed.gitee.io', resource_guid[4]),
            ('APP PORTAL', resource_guid[5]),
            (resource_guid[1], resource_guid[1]),
        ]
        for i in table:
            with self.subTest():
                res = self.client.get_subscriptionid_by_name(i[0])
                self.assertEqual(res, i[1])
        
    def test_get_subscriptionid_by_name_accept_id_false(self):
        """测试方法：get_subscriptionid_by_name
        accept_id: 参数设置为False
        """
        table = [
            ('NotExistName', None),
            ('Steed Xu', resource_guid[1]),
            ('Jeff Hee', resource_guid[2]),
            ('MAJAC', resource_guid[3]),
            ('steeed.gitee.io', resource_guid[4]),
            ('APP PORTAL', resource_guid[5]),
            (resource_guid[1], None),
        ]
        for i in table:
            with self.subTest():
                res = self.client.get_subscriptionid_by_name(i[0], accept_id=False)
                self.assertEqual(res, i[1])

    def test_subscription_display_name(self):
        """测试方法：subscription_display_name"""
        res = "| extend subscriptionDisplayName=case(" \
            f"subscriptionId =~ '{resource_guid[1]}','{self.mock_method.return_value[0]['display_name']}'," \
            f"subscriptionId =~ '{resource_guid[2]}','{self.mock_method.return_value[1]['display_name']}'," \
            f"subscriptionId =~ '{resource_guid[3]}','{self.mock_method.return_value[2]['display_name']}'," \
            f"subscriptionId =~ '{resource_guid[4]}','{self.mock_method.return_value[3]['display_name']}'," \
            f"subscriptionId =~ '{resource_guid[5]}','{self.mock_method.return_value[4]['display_name']}'," \
            "subscriptionId)"
        self.assertEqual(res, self.client.subscription_display_name())


if __name__ == '__main__':
    unittest.main()

